package cn.leida.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.boot.system.ApplicationPid;

import java.io.File;

/**
 * System.out.println("tasklist | findstr java");
 * System.out.println("taskkill /f /pid  " + pid.toString()) ;
 *
 * @author lei
 * @create 2025-05-23 22:01
 */
public class AppPidUtil {

    private static final String pidFilePath = ".data/app/app.pid";

    private static final String lockFilePath = ".data/app/app.lock";

    private static File dataFile() {
        File pidFile = new File(pidFilePath);
        pidFile.getParentFile().mkdirs();
        return pidFile;
    }

    private static File launcherFile() {
        File pidFile = new File(".launcher/" + pidFilePath);
        pidFile.getParentFile().mkdirs();
        return pidFile;
    }

    public static void saveDataPid() {
        ApplicationPid pid = new ApplicationPid();
        FileUtil.writeUtf8String(pid.toString(), dataFile());
    }

    public static void lockApp() {
        FileUtil.writeUtf8String("lock", new File(lockFilePath));
    }
    public static void unlockApp() {
        FileUtil.writeUtf8String("unlock", new File(lockFilePath));
    }

    public static void killPid(File pidFile) {
        if (pidFile == null) {
            return;
        }
        if (!pidFile.exists()) {
            return;
        }
        if (!pidFile.isFile()) {
            return;
        }
        try {
            String appPid = FileUtil.readUtf8String(pidFile);
            if (StrUtil.isNotBlank(appPid)) {
                Runtime.getRuntime().exec("taskkill /f /pid  " + appPid);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void killDataPid() {
        killPid(dataFile());
    }

    public static void killLauncherFPid() {
        killPid(launcherFile());
    }

    public static void main(String[] args) {
        killDataPid();
    }


}
